 <template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" name="CustomersPoolForm">
          <a-row>
						<a-col :span="24">
							<a-form-item label="统一社会信用代码" v-bind="validateInfos.customerNumber" id="CustomersPoolForm-customerNumber" name="customerNumber">
								<a-input v-model:value="formData.customerNumber" placeholder="统一社会信用代码"  :allow-clear="!disabled" ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="客户公司名" v-bind="validateInfos.customerName" id="CustomersPoolForm-customerName" name="customerName">
								<a-input v-model:value="formData.customerName" placeholder="请输入客户公司名"  :allow-clear="!disabled"  ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="引流人真实姓名" v-bind="validateInfos.createBy" id="CustomersPoolForm-createBy" name="createBy">
								<a-input v-model:value="formData.createBy" placeholder="请输入引流人真实姓名"  :allow-clear="!disabled"  ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="客户来源渠道" v-bind="validateInfos.sourceChannel" id="CustomersPoolForm-sourceChannel" name="sourceChannel">
								<j-dict-select-tag v-model:value="formData.sourceChannel" dictCode="come_channel" placeholder="请选择客户来源渠道"  allow-clear :show-arrow="!disabled"/>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="分配状态" v-bind="validateInfos.status" id="CustomersPoolForm-status" name="status">
								<j-dict-select-tag v-model:value="formData.status" dictCode="customer_status" placeholder="请选择分配状态"  allow-clear :show-arrow="!disabled"/>
							</a-form-item>
						</a-col>
<!--            <a-col :span="24">-->
<!--              <a-form-item label="负责人" v-bind="validateInfos.responsibleName" id="CustomersPoolForm-responsibleName" name="responsibleName">-->
<!--                <a-input v-model:value="formData.responsibleName" placeholder="请输入负责人" :allow-clear="!disabled" style="width: 100%;" ></a-input>-->
<!--              </a-form-item>-->
<!--            </a-col>-->
            <a-col :span="24">
              <a-form-item label="注册资本(万元)" v-bind="validateInfos.registeredCapital" id="CustomersPoolForm-registeredCapital" name="registeredCapital">
                <a-input v-model:value="formData.registeredCapital" placeholder="请输入注册资本（万元）" :allow-clear="!disabled" style="width: 100%;" ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="行业" v-bind="validateInfos.industry" id="CustomersPoolForm-industry" name="industry">
                <a-input v-model:value="formData.industry" placeholder="请输入行业" :allow-clear="!disabled" style="width: 100%;" ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="经营范围" v-bind="validateInfos.businessScope" id="CustomersPoolForm-businessScope" name="businessScope">
                <a-textarea v-model:value="formData.businessScope" placeholder="请输入经营范围" :allow-clear="!disabled" :rows="3" style="width: 100%;" ></a-textarea>
              </a-form-item>
            </a-col>

<!--            引流管理 新增按钮隐藏 需求升级来源客户编号和创建时间-->
						<a-col :span="24">
							<a-form-item label="需求升级来源客户编号" v-bind="validateInfos.parentCustomerId" id="CustomersPoolForm-parentCustomerId" name="parentCustomerId" v-if="false">
								<a-input v-model:value="formData.parentCustomerId" placeholder="请输入需求升级来源客户编号"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="创建时间" v-bind="validateInfos.createTime" id="CustomersPoolForm-createTime" name="createTime" v-if="false">
                <a-date-picker
                   placeholder="请选择创建时间"
                   v-model:value="formData.createTime"
                   picker="date"
                   value-format="YYYY-MM-DD"
                   style="width: 100%"
                   allow-clear
              />
              </a-form-item>
						</a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>

  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import { getValueType } from '/@/utils';
  import {saveOrUpdate} from '../CustomersPool.api';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';

  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({}) },
    formBpm: { type: Boolean, default: true }
  });
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok', 'taskAllocation']);
  const formData = reactive<Record<string, any>>({
        id: '',
        customerNumber: '',         //客户编号
        customerName: '',       //客户公司名
        createBy: '',           //引流人真实姓名
        sourceChannel: '0',     //客户来源渠道 - 默认为单条导入
        status: '0',            //分配状态
        registeredCapital: '',    //注册资本
        industry: '',           //行业
        businessScope: '',      //经营范围
        parentCustomerId: '',   //需求升级来源客户编号
        createTime:new Date().toISOString().split('T')[0],          //创建时间
  });



  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  // 新增模式与锁定状态
  const isAddMode = ref(false);
  const lockStatusOnAdd = ref(true);
  //表单验证
  const validatorRules = reactive({
    customerNumber: [{ required: true, message: '请输入统一社会信用代码!'},],
    customerName: [{ required: true, message: '请输入客户公司名!'},],
  });
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });
  const formRef = ref();
  // 表单禁用
  const disabled = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return false;
      }else{
        return true;
      }
    }
    return props.formDisabled;
  });

  
  /**
   * 新增
   */
  function add(initValues = {}) {
    // 设置新增时的默认值
    const defaultValues = {
      sourceChannel: '0', // 默认为单条导入
      // 分配状态：默认为“未确认”（按字典值设置）。若你的字典中“未确认”对应值不是 '0'，请替换此值
      status: '0',
      createTime: new Date().toISOString().split('T')[0], // 默认为当前日期
      ...initValues       // 允许传入的初始值覆盖默认值
    };
    isAddMode.value = true;
    edit(defaultValues);
  }

  /**
   * 编辑
   */
  
   function edit(record) {
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          if (key === 'status' && record[key] !== undefined) {
            tmpData[key] = String(record[key]);
          } else {
            tmpData[key] = record[key];
          }
        }
      })
      Object.assign(formData,tmpData);
       // 进入编辑模式
       isAddMode.value = !Boolean(record.id);
    });
  }





  /**
   * 提交数据
   */
  async function submitForm() {
    try {
      // 触发表单验证
      await validate();
    } catch (e: any) {
      if (e && e.errorFields) {
        const firstField = e.errorFields[0];
        if (firstField) {
          formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(e.errorFields);
    }
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }





  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }
  .a-input {
    margin-right: 16px; /* 增加输入框与按钮之间的间距 */
  }
</style>
